#include <chrono>
#include <future>
#include <iostream>
#include <thread>

#include "tools/threadsafe_queue.hpp"

threadsafe_queue<std::packaged_task<void()>> tasks;

// 模拟 GUI 关闭标志
bool shutdown = false;

// 模拟 GUI 消息是否收到
bool gui_shutdown_message_received()
{
    return shutdown;
}

// 模拟获取和处理 GUI 消息
void get_and_process_gui_message()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟消息处理延迟
    std::cout << "Processing GUI message..." << std::endl;
}

// GUI 线程
void gui_thread()
{
    while (!gui_shutdown_message_received()) {
        get_and_process_gui_message();
        std::packaged_task<void()> task;
        if (!tasks.wait_for_and_pop(task)) {
            continue;
        }
        task();
    }
}

// 向 GUI 线程发布任务
template <typename Func>
std::future<void> post_task_for_gui_thread(Func f)
{
    std::packaged_task<void()> task(f);
    std::future<void> res = task.get_future();
    tasks.push(std::move(task));
    return res;
}

int main()
{
    std::thread gui_bg_thread(gui_thread);

    // 发布几个任务到 GUI 线程
    auto fut1 = post_task_for_gui_thread([]() { std::cout << "Task 1 executed\n"; });
    auto fut2 = post_task_for_gui_thread([]() { std::cout << "Task 2 executed\n"; });

    fut1.get(); // 等待任务完成
    fut2.get();

    shutdown = true;
    gui_bg_thread.join();
    std::cout << "GUI thread exited\n";

    return 0;
}
